<template>
  <div class="inspection-record-container">
    <!-- 搜索区域 - 保持不变 -->
    <div class="search-container">
      <!-- 第一行搜索条件和按钮 -->
      <el-form ref="searchForm" :model="queryParams" label-width="80px" inline class="search-row first-row">
        <el-form-item label="生产主体">
          <el-input
            v-model="queryParams.entityName"
            size="small"
            placeholder="请输入生产主体"
            style="width: 200px;"
          ></el-input>
        </el-form-item>

        <el-form-item label="检查时间">
          <el-date-picker
            v-model="queryParams.inspectionTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            style="width: 300px;"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="省">
          <el-select
            v-model="queryParams.province"
            placeholder="请选择省"
            size="small"
            style="width: 180px;"
            @change="handleProvinceChange"
            :disabled="!isAdmin"
          >
            <el-option
              v-for="item in provinceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="市">
          <el-select
            v-model="queryParams.city"
            placeholder="请选择市"
            size="small"
            style="width: 180px;"
            :disabled="!queryParams.province || !isAdmin"
            @change="handleCityChange"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="区县">
          <el-select
            v-model="queryParams.district"
            placeholder="请选择区县"
            size="small"
            style="width: 200px;"
            :disabled="!queryParams.city || !isAdmin"
          >
            <el-option
              v-for="item in districtOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 搜索/重置/收起按钮 -->
        <el-form-item label-width="0">
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="small" style="margin-left: 10px;" @click="resetQuery">重置</el-button>
          <el-button type="text" size="small" style="margin-left: 10px;" @click="toggleSearch">收起</el-button>
        </el-form-item>
      </el-form>

      <!-- 第二行：操作按钮组 -->
      <el-form ref="searchForm3" :model="queryParams" label-width="80px" inline class="search-row second-row" v-if="searchExpanded">
        <el-form-item>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
          <el-button type="success" icon="el-icon-download" size="small" style="margin-left: 10px;" @click="handleExport">导出</el-button>
          <el-button type="danger" icon="el-icon-delete" size="small" style="margin-left: 10px;" @click="handleBatchDelete" v-if="selectedIds.length > 0">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 已选择区域 -->
    <el-row style="margin-bottom: 15px;">
      <el-col :span="24">
        <div class="selected-area">
          已选择{{ selectedIds.length }}项 <span class="clear-btn" @click="clearSelection">清空</span>
        </div>
      </el-col>
    </el-row>

    <!-- 表格区域 - 保持不变 -->
    <el-row>
      <el-col :span="24">
        <el-table
          ref="inspectionTable"
          :data="tableData"
          style="width: 100%"
          border
          stripe
          @selection-change="handleSelectionChange"
        >
          <!-- 选择框 -->
          <el-table-column type="selection" width="55" align="center"></el-table-column>

          <!-- 表头分组 -->
          <el-table-column label="基础信息" align="center">
            <el-table-column prop="inspectionDept" label="检查部门" align="center"></el-table-column>
            <el-table-column prop="inspectorName" label="检查人员" align="center"></el-table-column>
            <el-table-column prop="certificateCode" label="打印编号" align="center"></el-table-column>
            <el-table-column prop="entityName" label="生产主体" align="center"></el-table-column>
            <el-table-column prop="legalPerson" label="法人名称" align="center"></el-table-column>
            <el-table-column prop="contactPhone" label="联系电话" align="center"></el-table-column>
            <el-table-column prop="province" label="省" align="center"></el-table-column>
            <el-table-column prop="city" label="市" align="center"></el-table-column>
            <el-table-column prop="district" label="区县" align="center"></el-table-column>
            <el-table-column prop="town" label="镇乡" align="center"></el-table-column>
            <el-table-column prop="inspectionPlace" label="检查地点" align="center"></el-table-column>
          </el-table-column>

          <el-table-column label="检查记录" align="center">
            <el-table-column prop="inspectedProduct" label="产品名称" align="center"></el-table-column>
            <el-table-column label="合格证开具是否规范" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isStandard ? 'success' : 'danger'">
                  {{ scope.row.isStandard ? '合格' : '不合格' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="是否使用禁限用农药、兽药" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isForbiddenPesticide ? 'success' : 'danger'">
                  {{ scope.row.isForbiddenPesticide ? '合格' : '不合格' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="inspectionOpinion" label="检查意见" align="center"></el-table-column>
            <!-- 检查记录照片展示 -->
            <el-table-column label="检查记录照片" align="center" width="100">
              <template slot-scope="scope">
                <el-image
                  :src="getImageUrl(scope.row.photoUrls)"
                  style="width: 40px; height: 40px; cursor: pointer;"
                  fit="cover"
                  :preview-src-list="getPreviewImageList(scope.row.photoUrls)"
                ></el-image>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="其他记录" align="center">
            <el-table-column prop="inspectionTime" label="检查时间" align="center" :formatter="dateFormat"></el-table-column>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column fixed="right" label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-dropdown trigger="click">
                <span class="el-dropdown-link">
                  更多 <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu>
                  <el-dropdown-item @click.native="handleDelete(scope.row.id)">删除</el-dropdown-item>
                  <el-dropdown-item @click.native="handleDetail(scope.row)">详情</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 分页区域 - 保持不变 -->
    <el-row style="margin-top: 15px;">
      <el-col :span="24" align="center">
        <el-pagination
          layout="prev, pager, next, jumper, ->, total, sizes"
          :page-size="queryParams.pageSize"
          :total="total"
          :current-page="queryParams.pageNum"
          :page-sizes="[5, 10, 20, 50]"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </el-col>
    </el-row>

    <!-- 新增/编辑弹窗 - 修正产品名称字段映射 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增检查记录' : '编辑检查记录'"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="inspectionForm"
        :model="formData"
        label-width="120px"
        status-icon
      >
        <!-- 检查部门ID（必填项） -->
        <el-form-item label="检查部门ID" prop="deptId" :rules="[{ required: true, message: '请输入检查部门ID', trigger: 'blur' }]">
          <el-input
            v-model.number="formData.deptId"
            placeholder="请输入检查部门ID"
            type="number"
          ></el-input>
        </el-form-item>

        <!-- 检查部门名称 -->
        <el-form-item label="检查部门" prop="inspectionDept" :rules="[{ required: true, message: '请输入检查部门', trigger: 'blur' }]">
          <el-input
            v-model="formData.inspectionDept"
            placeholder="检查部门"
          ></el-input>
        </el-form-item>

        <!-- 检查人员ID（必填项） -->
        <el-form-item label="检查人员ID" prop="inspectorId" :rules="[{ required: true, message: '请输入检查人员ID', trigger: 'blur' }]">
          <el-input
            v-model.number="formData.inspectorId"
            placeholder="请输入检查人员ID"
            type="number"
          ></el-input>
        </el-form-item>

        <!-- 检查人员 -->
        <el-form-item label="检查人员" prop="inspectorName" :rules="[{ required: true, message: '请输入检查人员', trigger: 'blur' }]">
          <el-input
            v-model="formData.inspectorName"
            placeholder="检查人员"
          ></el-input>
        </el-form-item>

        <!-- 打印编号 -->
        <el-form-item label="打印编号" prop="certificateCode">
          <el-input
            v-model="formData.certificateCode"
            placeholder="请输入证书编号"
          ></el-input>
        </el-form-item>

        <!-- 生产主体信息 -->
        <el-form-item label="生产主体" prop="entityName" :rules="[{ required: true, message: '请输入生产主体', trigger: 'blur' }]">
          <el-input
            v-model="formData.entityName"
            placeholder="生产主体名称"
          ></el-input>
        </el-form-item>

        <!-- 法人姓名 -->
        <el-form-item label="法人姓名" prop="legalPerson" :rules="[{ required: true, message: '请输入法人姓名', trigger: 'blur' }]">
          <el-input
            v-model="formData.legalPerson"
            placeholder="法人姓名"
          ></el-input>
        </el-form-item>

        <!-- 联系方式 -->
        <el-form-item label="联系方式" prop="contactPhone" :rules="[{ required: true, message: '请输入联系方式', trigger: 'blur' }]">
          <el-input
            v-model="formData.contactPhone"
            placeholder="联系方式"
          ></el-input>
        </el-form-item>

        <!-- 检查产品（修正字段名，与数据库对应） -->
        <el-form-item label="产品名称" prop="inspectedProduct" :rules="[{ required: true, message: '请输入产品名称', trigger: 'blur' }]">
          <el-input
            v-model="formData.inspectedProduct"
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item>

        <!-- 检查地点 -->
        <el-form-item label="检查地点" prop="inspectionPlace" :rules="[{ required: true, message: '请输入检查地点', trigger: 'blur' }]">
          <el-input
            v-model="formData.inspectionPlace"
            placeholder="请输入检查地点"
          ></el-input>
        </el-form-item>

        <!-- 检查时间 -->
        <el-form-item label="检查时间" prop="inspectionTime" :rules="[{ required: true, message: '请选择检查时间', trigger: 'change' }]">
          <el-date-picker
            v-model="formData.inspectionTime"
            type="datetime"
            placeholder="选择检查时间"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>

        <!-- 检查意见 -->
        <el-form-item label="检查意见" prop="inspectionOpinion">
          <el-input
            v-model="formData.inspectionOpinion"
            placeholder="请输入检查意见"
            type="textarea"
            rows="3"
          ></el-input>
        </el-form-item>

        <!-- 合格证开具是否规范 -->
        <el-form-item label="合格证开具是否规范" prop="isStandard" :rules="[{ required: true, message: '请选择是否规范', trigger: 'change' }]">
          <el-select
            v-model="formData.isStandard"
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option label="合格" :value="1"></el-option>
            <el-option label="不合格" :value="0"></el-option>
          </el-select>
        </el-form-item>

        <!-- 是否使用禁限用农药 -->
        <el-form-item label="是否使用禁限用农药、兽药" prop="isForbiddenPesticide" :rules="[{ required: true, message: '请选择是否使用', trigger: 'change' }]">
          <el-select
            v-model="formData.isForbiddenPesticide"
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option label="合格" :value="1"></el-option>
            <el-option label="不合格" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入API接口
import { getList, getInfo, add, update, del, exportExcel } from '@/api/njt/member/inspectionRecord';

export default {
  name: "InspectionRecord",
  data() {
    return {
      // 加载状态
      loading: false,
      // 是否为管理员，控制省市区查询条件的显示
      isAdmin: true,
      // 表格数据
      tableData: [],
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        entityName: "",
        inspectionTimeRange: [],
        province: "",
        city: "",
        district: ""
      },
      // 省市区选项
      provinceOptions: [
        { value: "510000", label: "四川省" },
        { value: "500000", label: "重庆市" }
      ],
      cityOptions: [],
      districtOptions: [],
      // 弹窗控制
      dialogVisible: false,
      dialogType: "add",
      // 表单数据 - 修正产品名称字段为inspectedProduct
      formData: {
        id: undefined,
        deptId: null,  // 检查部门ID
        inspectorId: null,  // 检查人员ID
        certificateCode: "",
        inspectorName: "",
        inspectionDept: "",  // 检查部门名称
        entityName: "",
        legalPerson: "",
        contactPhone: "",
        inspectedProduct: "",  // 产品名称，与数据库inspected_product对应
        inspectionPlace: "",
        inspectionTime: new Date(),
        inspectionOpinion: "",
        isStandard: 1,
        isForbiddenPesticide: 1,
        photoUrls: ""
      },
      // 已选择的记录ID
      selectedIds: [],
      // 搜索区域是否展开
      searchExpanded: true
    };
  },

  created() {
    this.getList();
  },

  methods: {
    // 日期格式化方法
    dateFormat(row, column, cellValue) {
      if (!cellValue) return '';
      const date = new Date(cellValue);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
    },

    // 获取列表数据
    getList() {
      this.loading = true;
      getList(this.queryParams).then(response => {
        if (response && response.rows) {
          this.tableData = response.rows;
          this.total = response.total || 0;
        } else {
          this.tableData = response || [];
          this.total = this.tableData.length;
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.$message.error('获取数据失败，请刷新页面重试');
        this.loading = false;
      });
    },

    // 处理查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置查询条件
    resetQuery() {
      if (this.$refs.searchForm) {
        this.$refs.searchForm.resetFields();
      }
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        entityName: "",
        inspectionTimeRange: [],
        province: "",
        city: "",
        district: ""
      };
      this.getList();
    },

    // 切换搜索区域展开/收起
    toggleSearch() {
      this.searchExpanded = !this.searchExpanded;
    },

    handleAdd() {
      this.dialogType = 'add';
      // 重置表单数据
      this.formData = {
        id: undefined,
        deptId: null,
        inspectorId: null,
        certificateCode: "",
        inspectorName: "",
        inspectionDept: "",
        entityName: "",
        legalPerson: "",
        contactPhone: "",
        inspectedProduct: "",  // 初始化产品名称字段
        inspectionPlace: "",
        inspectionTime: new Date(),
        inspectionOpinion: "",
        isStandard: 1,
        isForbiddenPesticide: 1,
        photoUrls: ""
      };
      this.dialogVisible = true;
    },

    handleEdit(row) {
      this.dialogType = 'edit';
      // 调用接口获取详情数据
      getInfo(row.id).then(response => {
        if (response && response.data) {
          const recordData = response.data;
          // 填充表单数据，确保产品名称映射正确
          this.formData = {
            ...recordData,
            id: Number(recordData.id),
            deptId: recordData.deptId ? Number(recordData.deptId) : null,
            inspectorId: recordData.inspectorId ? Number(recordData.inspectorId) : null,
            inspectionTime: recordData.inspectionTime ? new Date(recordData.inspectionTime) : null,
            isStandard: recordData.isStandard !== undefined ? Number(recordData.isStandard) : 1,
            isForbiddenPesticide: recordData.isForbiddenPesticide !== undefined ? Number(recordData.isForbiddenPesticide) : 1,
            // 确保产品名称正确映射
            inspectedProduct: recordData.inspectedProduct || recordData.productName || ""
          };
          this.dialogVisible = true;
        } else {
          this.$message.error('获取记录详情失败：数据为空');
        }
      }).catch(error => {
        console.error('获取详情失败:', error);
        this.$message.error(`获取记录详情失败：${error.response?.data?.msg || error.message || '未知错误'}`);
      });
    },

    // 处理详情查看
    handleDetail(row) {
      this.$alert(`
        检查部门: ${row.inspectionDept || '无'}<br>
        检查人员: ${row.inspectorName || '无'}<br>
        生产主体: ${row.entityName || '无'}<br>
        产品名称: ${row.inspectedProduct || row.productName || '无'}<br>
        证书编号: ${row.certificateCode || '无'}<br>
        检查时间: ${this.dateFormat(null, null, row.inspectionTime) || '无'}<br>
        检查意见: ${row.inspectionOpinion || '无'}
      `, '检查记录详情', {
        dangerouslyUseHTMLString: true
      });
    },

    // 提交表单
    submitForm() {
      this.$refs.inspectionForm.validate(valid => {
        if (valid) {
          const submitData = { ...this.formData };

          // 确保ID字段为数值类型
          if (submitData.deptId) {
            submitData.deptId = Number(submitData.deptId);
          }
          if (submitData.inspectorId) {
            submitData.inspectorId = Number(submitData.inspectorId);
          }

          // 处理日期格式
          if (submitData.inspectionTime) {
            submitData.inspectionTime = new Date(submitData.inspectionTime).toISOString();
          }

          // 字段映射，确保与数据库表结构一致
          submitData.deptName = submitData.inspectionDept;
          // 确保产品名称正确传递给inspected_product字段
          submitData.inspectedProduct = submitData.inspectedProduct.trim();

          if (this.dialogType === 'add') {
            add(submitData).then(() => {
              this.$message.success('新增成功');
              this.dialogVisible = false;
              this.getList();
            }).catch(error => {
              console.error('新增失败:', error);
              this.$message.error('新增失败: ' + (error.response?.data?.msg || '网络错误'));
            });
          } else {
            update(submitData).then(() => {
              this.$message.success('编辑成功');
              this.dialogVisible = false;
              this.getList();
            }).catch(error => {
              console.error('编辑失败:', error);
              this.$message.error('编辑失败: ' + (error.response?.data?.msg || '网络错误'));
            });
          }
        }
      });
    },

    // 其他方法保持不变...
    handleDelete(id) {
      if (!id) {
        this.$message.error('无效的记录ID');
        return;
      }

      this.$confirm('确定要删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(() => {
          this.$message.success('删除成功');
          this.getList();
        }).catch(error => {
          console.error('删除失败:', error);
          this.$message.error('删除失败: ' + (error.response?.data?.msg || '网络错误'));
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请先选择要删除的记录');
        return;
      }

      this.$confirm(`确定要删除选中的${this.selectedIds.length}条记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(this.selectedIds.join(',')).then(() => {
          this.$message.success('批量删除成功');
          this.selectedIds = [];
          this.getList();
        }).catch(error => {
          console.error('批量删除失败:', error);
          this.$message.error('批量删除失败: ' + (error.response?.data?.msg || '网络错误'));
        });
      }).catch(() => {
        this.$message.info('已取消批量删除');
      });
    },

    handleExport() {
      exportExcel(this.queryParams).then(response => {
        const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
        const fileName = `检查记录_${new Date().getTime()}.xlsx`;

        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          const link = document.createElement('a');
          const href = window.URL.createObjectURL(blob);
          link.href = href;
          link.download = fileName;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(href);
        }
        this.$message.success('导出成功');
      }).catch(error => {
        console.error('导出失败:', error);
        this.$message.error('导出失败: ' + (error.response?.data?.msg || '网络错误'));
      });
    },

    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id);
    },

    clearSelection() {
      this.$refs.inspectionTable.clearSelection();
      this.selectedIds = [];
    },

    handleProvinceChange(provinceCode) {
      this.queryParams.city = '';
      this.queryParams.district = '';
      this.districtOptions = [];

      if (provinceCode === '510000') {
        this.cityOptions = [
          { value: '510100', label: '成都市' },
          { value: '510200', label: '重庆市' },
          { value: '510300', label: '自贡市' }
        ];
      } else if (provinceCode === '500000') {
        this.cityOptions = [
          { value: '500100', label: '渝中区' },
          { value: '500200', label: '万州区' },
          { value: '500300', label: '涪陵区' }
        ];
      } else {
        this.cityOptions = [];
      }
    },

    handleCityChange(cityCode) {
      this.queryParams.district = '';
      this.districtOptions = [
        { value: cityCode + '01', label: '市辖区1' },
        { value: cityCode + '02', label: '市辖区2' },
        { value: cityCode + '03', label: '市辖区3' }
      ];
    },

    getImageUrl(url) {
      if (!url || url === '无') {
        return require('@/assets/images/profile.jpg');
      }

      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      if (!url.startsWith('/')) {
        url = '/' + url;
      }
      return process.env.VUE_APP_BASE_API + url;
    },

    getPreviewImageList(urls) {
      if (!urls || urls === '无') return [];
      return urls.split(',').map(url => this.getImageUrl(url));
    }
  }
};
</script>

<style scoped>
.inspection-record-container {
  padding: 15px;
  background-color: #fff;
  min-height: calc(100vh - 120px);
}

.search-container {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-row {
  margin-bottom: 10px;
}

.second-row {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #e4e7ed;
}

.selected-area {
  padding: 8px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.clear-btn {
  color: #409eff;
  cursor: pointer;
  margin-left: 10px;
}

.clear-btn:hover {
  text-decoration: underline;
}
</style>
